<?php

namespace app\console\command;

use app\common\model\Vod;
use Aws\AwsService;
use CloudFlare\CloudFlareApiClient;
use HuaweiVod\HuaweiVod;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;

class FixCloudflareVod extends Command
{
    protected function configure()
    {
        $this->setName('fix_cloudflare_vod')
            ->setDescription('fix cloudflare vod');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->info("execute fix cloudflare");
        try {
            $vodList = Db::name('vod')->where('status', '=', Vod::VOD_STATUS_NO_UPLOAD)
                ->where('platform', '=', 'cloudflare')
                ->where('url', '<>', '')
                ->select();
            foreach ($vodList as $vod) {
                try {
                    Log::info('begin to fix vod:' . $vod['id']);
                    if ($this->isStorageFull()) {
                        Log::info('storage is full');
                        break;
                    }

                    $this->fixVod($vod['id']);
                    sleep(1);
                } catch (\Exception $exception) {
                    Log::error($exception->getMessage());
                    Log::error($exception->getTraceAsString());
                }
            }
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
            Log::error($exception->getTraceAsString());
//            $output->error($exception->getMessage());
        }
    }

    protected function fixVod($vodId)
    {
        $vod = Db::name('vod')->where(['id' => $vodId])->find();

        $title = $vod['video_name'];
        $cfClient = new CloudFlareApiClient();
        $result = $cfClient->postUploadVideo($vod['url'], $title);
        if ($result) {
            if (is_string($result)) {
                $result = json_decode($result, true);
            }
            Log::info('result:' . json_encode($result));
            if ($result['success'] == false) {
                Log::error('upload vod video failed');
                return;
            }
            $status = Vod::VOD_STATUS_NO_UPLOAD;
            if ($result['result']['status'] == 'ready') {
                $status = Vod::VOD_STATUS_UPLOADED;
            }

            $attr['video_type'] = 'M3U8';
            if (!empty($result['result']['uid'])) {
                $attr['asset_id'] = $result['result']['uid'];
                $attr['url'] = $result['result']['playback']['hls'];
            }
            $attr['status'] = $status;
            Vod::where(['id' => $vod['id']])->update($attr);
        }
    }

    protected function isStorageFull()
    {
        $cfClient = new CloudFlareApiClient();
        $result = $cfClient->getStorageUseage();
        if ($result) {
            if (is_string($result)) {
                $result = json_decode($result, true);
            }
            Log::info('storage result:' . json_encode($result));
            if ($result['success'] == false) {
                Log::error('get storage failed');
                return false;
            }
            if ($result['result']['totalStorageMinutes'] >= ($result['result']['totalStorageMinutesLimit'] - 10)) {
                return true;
            }
        }
        return false;

    }
}
